好的今天來為代辦清單新增計數功能和日期顯示
我們先來處理計數功能,會顯示總任務數量及已完成數量
在<script setup>
區域修改import那行,加入computed
import { ref, computed } from 'vue'
computed 一個計算屬性,有資料變化時會自動重新計算結果。資料沒變化,則會快取之前的結果
加入下面兩行程式
const totalCount = computed(() => tasks.value.length)
const doneCount = computed(() => tasks.value.filter(t => t.done).length)
const totalCount = computed(() => tasks.value.length)
設定一個變數totalCount用來顯示目前總事項數量.length
會回傳陣列長度,所以tasks.value.length
會回傳目前代辦事項陣列內有多少代辦事項
const doneCount = computed(() => tasks.value.filter(t => t.done).length)
設定一個變數doneCount來記錄已完成的數量tasks.value.filter(...)
會建立一個新陣列,包含符合條件的項目t => t.done
是箭頭函式,表示只留下done屬性為true的事項,也是.filter
判斷的條件
接著來處理自動生成日期的功能
// === 日期標題 ===
const todayTitle = computed(() => {
const today = new Date()
const month = today.getMonth() + 1
const date = today.getDate()
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
const weekday = weekdays[today.getDay()]
return `${month}/${date} (${weekday}) 代辦事項清單`
const today = new Date()
建立一個新的Date物件,會自動抓取當下系統的時間,靠JavaScript內建的Date物件來完成const month = today.getMonth() + 1
用變數month取得月份,因為JavaScript的getMonth()是從0開始的,所以要加一const date = today.getDate()
用變數date取得日期const weekdays = ['日', '一', '二', '三', '四', '五', '六']
定義一個陣列,讓0~6對應星期const weekday = weekdays[today.getDay()]
today.getDay()會回傳0~6,對應星期幾後再傳給weekday
return ${month}/${date} (${weekday}) 代辦事項清單
組成字串後回傳
好的接著到<template>
區域將這兩項功能放進去
<template>
<div class= "container">
<div class="box1"> </div>
<div class="box2">
<!-- 標題 (日期) -->
<h1>{{ todayTitle }}</h1>
<!-- 輸入框 -->
<div class="input-box">
<input v-model="newTask" placeholder="輸入新的代辦事項..." @keyup.enter="addTask" />
<button @click="addTask">新增</button>
</div>
<!-- 計數 -->
<div>
<p>總任務數: {{ totalCount }} | 已完成: {{ doneCount }}</p>
</div>
<!-- 清單 -->
<ul class="task-list">
<li v-for="(task, index) in tasks" :key="index" :class="{ done: task.done }">
<span @click="toggleTask(index)">
<input
type="checkbox"
v-model="task.done"
/>{{ task.text }}</span>
<button class="delete" @click="deleteTask(index)">刪除</button>
</li>
</ul>
</div>
<div class="box3"> </div>
</div>
</template>
如果想修改樣式一樣可以在<style scoped>
區域添加樣式
這裡小提一下,我有在代辦事項前加入一個小方框可以打勾,只要修改<span>
那行程式
<span @click="toggleTask(index)">
<input
type="checkbox"
v-model="task.done"
/>{{ task.text }}</span>
將<span>
那行改成上面的範例就好
然後在<style scoped>
添加樣式設定
.task-list li span {
cursor: pointer;
display: flex;
align-items: center; /* ✅ 讓 checkbox 和文字垂直置中 */
}
/* 完成的項目 */
.task-list li.done span {
text-decoration: line-through;
color: gray;
}
.task-list input[type="checkbox"] {
width: 18px;
height: 18px;
accent-color: #43917f; /* ✅ 設定勾選顏色 (大部分現代瀏覽器支援) */
cursor: pointer;
margin-right: 8px; /* 與文字的間距 */
}
目前的畫面長這樣
好的今天先分享到這
各位明天見~